package com.meaningful.multithreading_and_concurrency.what;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {

    public static void main(String[] args) throws InterruptedException {
        // 定义线程的数量
        final int threadSize = 1000;

        // 创建一个线程不安全的实例对象
        ThreadUnsafeExample example = new ThreadUnsafeExample();

        // 使用 CDL 来同步线程
        // 初始化计数器为线程数量(1000)，每个线程执行完后计数器减一
        final CountDownLatch countDownLatch = new CountDownLatch(threadSize);

        // 创建一个线程池，使用newCachedThreadPool动态调整线程数量
        ExecutorService executorService = Executors.newCachedThreadPool();

        // 循环创建并提交任务到线程池
        for (int i = 0; i < threadSize; i++) {
            executorService.execute(() -> {
                // 每个线程调用 add
                example.add();
                // 计数器-1
                countDownLatch.countDown();
            });
        }
        // 等待主线程执行完毕
        countDownLatch.await();

        // 关闭线程池
        executorService.shutdown();
        System.out.println(example.get());
    }

}
